/**
 * 
 */
package kit4j.ui.cs.swing.dnd;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author MiniKnife
 *
 */
public class LocalObjectRefTransferable implements Transferable {

	private Serializable object;

	private List<DataFlavor> flavorList;

	public LocalObjectRefTransferable(Serializable object) {
		this.object = object;
		flavorList = createDataFlavorWithObject(object);
	}

	private List<DataFlavor> createDataFlavorWithObject(Object object) {
		List<DataFlavor> flavorList = new ArrayList<DataFlavor>();
		flavorList.add(DataFlavor.stringFlavor);

		try {
			Class<?> type = object.getClass();
			String mimeType = null;
			while (type != null) {
				mimeType = DataFlavor.javaJVMLocalObjectMimeType + ";class="
						+ type.getCanonicalName();
				flavorList.add(new DataFlavor(mimeType));

				type = type.getSuperclass();
			}
		} catch (ClassNotFoundException e) {
		}

		return flavorList;
	}

	/**
	 * @see java.awt.datatransfer.Transferable#getTransferData(java.awt.datatransfer.DataFlavor)
	 */
	@Override
	public Object getTransferData(DataFlavor flavor)
			throws UnsupportedFlavorException, IOException {
		if (!isDataFlavorSupported(flavor)) {
			throw new UnsupportedFlavorException(flavor);
		}

		if (DataFlavor.stringFlavor.equals(flavor)) {
			return object.toString();
		}

		return object;
	}

	/**
	 * @see java.awt.datatransfer.Transferable#getTransferDataFlavors()
	 */
	@Override
	public DataFlavor[] getTransferDataFlavors() {
		return flavorList.toArray(new DataFlavor[0]);
	}

	/**
	 * @see java.awt.datatransfer.Transferable#isDataFlavorSupported(java.awt.datatransfer.DataFlavor)
	 */
	@Override
	public boolean isDataFlavorSupported(DataFlavor flavor) {
		return flavorList.contains(flavor);
	}

}
